/**
 * Aibton.com Inc.
 * Copyright (c) 2004-2017 All Rights Reserved.
 */
package com.example.demo.common;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理
 * @author dengkaixian
 */
@RestControllerAdvice
public class GlobalExceptionAdvice  {

    private String profile;
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionAdvice.class);
    private ResultObject result = new ResultObject();

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    public ResultObject handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        result.setError("500");
        result.setErrorCode(BaseErrorConfigEnum.FAIL.name());
        result.setMessage("不支持' " + e.getMethod() + "'请求");
        return result;
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResultObject notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        result.setError("500");
        result.setErrorCode(BaseErrorConfigEnum.FAIL.name());
        result.setMessage("运行时异常:" + e.getMessage());
        return result;
    }

    /**
     * 业务参数校验异常
     */
    @ExceptionHandler(RequestException.class)
    public ResultObject  handleRequestException(RequestException e) {
        log.error(e.getMessage(), e);
        result.setError(e.getiEnum().getCode());
        result.setErrorCode(e.getiEnum().getName());
        result.setMessage(e.getiEnum().getValue());
        return result;
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResultObject  handleException(Exception e) {
        log.error(e.getMessage(), e);
        result.setError("500");
        result.setErrorCode(BaseErrorConfigEnum.FAIL.name());
        result.setMessage("服务器错误，请联系管理员");
        return result;
    }
}
